const { meetingAPI } = require('../../utils/util.js')

Page({
  data: {
    meeting: {},
    isLoading: true,
    error: false,
    errorMsg: '',
    type: '',
    detail: null
  },

  onLoad(options) {
    const meetingId = options.id;
    if (meetingId) {
      this.fetchMeetingDetail(meetingId);
    } else {
        this.setData({
        error: true, 
        errorMsg: '会议ID不能为空',
        isLoading: false 
      });
    }
  },

  // 从后端API获取会议详情
  fetchMeetingDetail(meetingId) {
    this.setData({ isLoading: true, error: false });
    
    // 由于后端没有提供获取单个会议详情的接口，我们通过列表接口获取
    meetingAPI.getMeetingList({ currentUserId: 1 })
      .then(res => {
        console.log('会议数据获取成功:', res);
        
        if (res.code === 200) {
          // 从搜索结果中找到对应的会议
          const meeting = res.data.find(item => item.meetingId == meetingId);
          
          if (meeting) {
            // 转换数据格式以适配前端显示
            const meetingDetail = {
              id: meeting.meetingId,
              title: meeting.meetingName,
              cover: this.buildImageUrl(meeting.meetingCover),
              startTime: this.formatDateTime(meeting.startTime),
              endTime: this.formatDateTime(meeting.endTime),
              creator: meeting.creatPerson,
              content: this.cleanHtmlTags(meeting.meetingContent)
            };
            
            this.setData({ 
              meeting: meetingDetail, 
              isLoading: false 
            });
          } else {
        this.setData({
              error: true, 
              errorMsg: '会议不存在',
              isLoading: false 
            });
          }
        } else {
          this.setData({ 
            error: true, 
            errorMsg: res.message || '获取会议详情失败',
            isLoading: false 
          });
        }
      })
      .catch(err => {
        console.error('获取会议详情失败:', err);
        this.setData({
          error: true, 
          errorMsg: '网络请求失败',
          isLoading: false 
        });
        });
  },

  // 格式化日期时间
  formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '';
    const date = new Date(dateTimeStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}`;
  },

  // 构建图片URL
  buildImageUrl(imageName) {
    if (!imageName) {
      return 'https://picsum.photos/750/300?random=1'; // 默认图片
    }
    // 如果已经是完整URL，直接返回
    if (imageName.startsWith('http://') || imageName.startsWith('https://')) {
      return imageName;
    }
    // 构建完整的图片URL
    return `${getApp().globalData.apiBaseUrl}/images/${imageName}`;
  },

  // 清理HTML标签
  cleanHtmlTags(htmlContent) {
    if (!htmlContent) return '';
    
    // 移除HTML标签，保留文本内容
    return htmlContent
      .replace(/<p[^>]*>/gi, '') // 移除开始p标签
      .replace(/<\/p>/gi, '\n') // 将结束p标签替换为换行
      .replace(/<br[^>]*>/gi, '\n') // 将br标签替换为换行
      .replace(/<[^>]+>/g, '') // 移除其他所有HTML标签
      .replace(/&nbsp;/g, ' ') // 将&nbsp;替换为空格
      .replace(/&amp;/g, '&') // 将&amp;替换为&
      .replace(/&lt;/g, '<') // 将&lt;替换为<
      .replace(/&gt;/g, '>') // 将&gt;替换为>
      .replace(/&quot;/g, '"') // 将&quot;替换为"
      .trim(); // 去除首尾空格
  },

  // 跳转参会回执页
  goRegistration() {
    wx.navigateTo({
      url: `/pages/meetingregist/registration?id=${this.data.meeting.id}`,
    });
  },

  // 分享逻辑
  onShareAppMessage() {
    return {
      title: `【${this.data.meeting.title}】来自测盟汇的合作会议`,
      path: `/pages/meetingregist/detail?id=${this.data.meeting.id}`,
      imageUrl: this.data.meeting.cover,
    };
  },

  // 封面加载失败兜底
  onCoverError() {
    this.setData({ 'meeting.cover': '/assets/icons/default-cover.png' });
  },

  // 重新加载（错误时）
  reloadData() {
    this.fetchMeetingDetail(this.data.meeting.id);
  },
});